package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func main() {
	engine := gin.Default()
	student := engine.Group("/student")
	{
		student.Use(PerformanceFilter()).Use(LoginFilter())
		student.GET("/get", studentGet)
		student.GET("/delete", deleteGet)
	}
	person := engine.Group("/person")
	{
		person.GET("/get", personGet)
		person.GET("/delete", deletePerson)
	}
	engine.Run()
}

func deletePerson(c *gin.Context) {
	c.String(http.StatusOK, "delete person")
}

func personGet(c *gin.Context) {
	c.String(http.StatusOK, "get person")
}

func studentGet(c *gin.Context) {
	uid, _ := c.Get("uid")
	c.JSON(http.StatusOK, gin.H{
		"errno": 0,
		"errmsg": "get student success",
		"data": fmt.Sprintf("{\"uid\": %v}", uid),
	})
	//c.String(http.StatusOK, "get student")
}
func deleteGet(c *gin.Context) {
	c.String(http.StatusOK, "delete student")
}

func LoginFilter() gin.HandlerFunc {
	return func(c *gin.Context) {
		uid, err := c.Cookie("uid")
		if err != nil {
			fmt.Println("not login")
			c.JSON(http.StatusUnauthorized, gin.H{
				"errNo": 100,
				"errMsg": "not login",
			})
			c.Abort()	//未登录，直接拦截
			return
		}

		fmt.Println("uid = ", uid)
		c.Set("uid", uid)
		c.Next()
	}
}

func PerformanceFilter() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		c.Next()

		end := time.Now()
		cost := end.Sub(start)
		fmt.Println("cost is :", cost)

	}
}